package cn.com.libertymutual.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import cn.com.libertymutual.core.base.dto.UserInfo;
import cn.com.libertymutual.core.exception.CustomLangException;
import cn.com.libertymutual.core.exception.SysExceptionEnums;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.util.uuid.UUID;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sys.bean.SysRole;
import cn.com.libertymutual.sys.bean.SysUser;
import cn.com.libertymutual.sys.dao.ISysRoleDao;
import cn.com.libertymutual.sys.dao.ISysUserDao;
import cn.com.libertymutual.sys.service.api.ISysUserService;
import cn.com.libertymutual.sys.service.api.ISystemService;
import cn.com.libertymutual.sys.vo.MenuInfoVO;
@Service("sysUserService")
public class SysUserServiceImpl implements ISysUserService{
	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired ISysUserDao userDao;
	@Autowired ISysRoleDao roleDao;
	@Autowired ISystemService systemService;
	@Override
	public ServiceResult findAll(boolean isLookup, String lookupDataOne,
			String lookupDataTwo, int pageNumber, int pageSize,
			String sortfield, String sorttype) {
		ServiceResult sr=new ServiceResult();
		Sort sort=null;
		if("ASC".equals(sorttype) ){
			sort =new Sort(Direction.ASC,sortfield);
		}else{
			sort =new Sort(Direction.DESC,sortfield);
		}
		if(isLookup){
			//设置查询条件 
			sr.setResult(userDao.findAll(new Specification<SysUser>(){
				@Override
				public Predicate toPredicate(Root<SysUser> root,
						CriteriaQuery<?> query, CriteriaBuilder cb) {
					List<Predicate> list = new ArrayList<>();
					list.add(cb.like(root.get("userid").as(String.class),"%"+lookupDataOne+"%"));
					list.add(cb.like(root.get("username").as(String.class),"%"+lookupDataTwo+"%"));
					Predicate[] p = new Predicate[list.size()];
		
					return cb.and(list.toArray(p));
				}},PageRequest.of(pageNumber - 1, pageSize, sort)));
		}else{
			sr.setResult(userDao.findAll(PageRequest.of(pageNumber - 1, pageSize, sort)));
		}
		return sr;
	}
	
	
	@Override
	public UserInfo initUser(String userId ) {
		UserInfo user= new UserInfo();
		SysUser sysuser = null;
		sysuser  =	userDao.findByUserid(userId);
		if(sysuser==null || sysuser.getStatus() == "0"){
			List<SysUser> sysusers  =	userDao.findByMobile(userId);
			if (CollectionUtils.isNotEmpty(sysusers)) {
				sysuser = sysusers.get(0);
			}else {
				log.error(SysExceptionEnums.SYS_USER_ERROR_EXCEPTION.getMessage()); 
				throw new CustomLangException(SysExceptionEnums.SYS_USER_ERROR_EXCEPTION);
			}
		}
		user.setTokenId(UUID.getUUIDString());
		user.setBranchNo(sysuser.getBranchcode());
		//user.setBranchName(sysuser.);
		user.setDepartmentCode(sysuser.getDeptcode());
		user.setUserId(sysuser.getUserid());
		user.setUserName(sysuser.getUsername());
		log.info("----------userId---cccccccccccccc------{}",userId);
		List<Integer> roles = roleDao.findRolesByUserId(userId); 
		List<String > roleIds= Lists.newArrayList();
		List<String > approve= Lists.newArrayList();
		List<String > config= Lists.newArrayList();
		if(roles!=null ){
			for(Integer role: roles ){
				SysRole rr = roleDao.findByRoleid(role);
				approve.add(rr.getApproveAuth().toString());			
				roleIds.add(role.toString());
				config.add(rr.getConfigAuth().toString());
			}
		}
		user.setUserCode(StringUtils.isNotBlank(sysuser.getUserCode())?sysuser.getUserCode():"");
		user.setRoleId(roleIds); 
		user.setApprove(approve);
		user.setConfigAuth(config);
		user.setMobile(sysuser.getMobileno());
		List<MenuInfoVO> mm = systemService.getAccessMenuInfo(1, roleIds,sysuser.getUserid());
		user.setMenus(mm );
		sysuser.setLastlogindate(new Date());
		sysuser.setLoginnum(sysuser.getLoginnum()+1);
		sysuser.setLoginip(Current.IP.get());
		userDao.save(sysuser);
		Current.sysuser.set(sysuser);
		Current.userInfo.set(user);
		Current.userId.set(userId); 
		return user;
	} 
	
}
